package com.jzo2o.orders.manager.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersCanceled;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liuyp
 * @since 2024/12/23
 */
@Slf4j
@Component
public class OrdersHandler {

    @Resource
    private IOrdersManagerService ordersManagerService;
    @Resource
    private IOrdersRefundService ordersRefundService;

    /**
     * 定时扫描超时未支付的订单，然后取消订单
     */
    @XxlJob("cancelOverTimePayOrder")
    public void cancelOverTimePayOrder(){
        //1. 查询出100个超时未支付的订单
        List<Orders> list = ordersManagerService.queryOverTimeNoPayOrdersByCount(100);
        if (CollUtil.isEmpty(list)) {
            return;
        }

        //2. 挨个取消订单（都是未支付状态的订单，需要修改orders表的order_status，新增order_canceled表记录）
        for (Orders orders : list) {
            OrderCancelDTO dto = BeanUtil.toBean(orders, OrderCancelDTO.class);
            dto.setId(orders.getId());
            dto.setCurrentUserType(UserType.SYSTEM);
            dto.setCancelReason("超时未支付自动取消订单");
            ordersManagerService.cancelNoPayOrder(dto);
        }
    }

    @XxlJob("handleRefundOrders")
    public void handleRefundOrders(){
        //1. 先查询待退款记录
        List<OrdersRefund> ordersRefunds = ordersRefundService.queryRefundOrderListByCount(100);
        if (CollUtil.isEmpty(ordersRefunds)) {
            return;
        }
        //2. 为这些待退款的订单处理退款操作
        for (OrdersRefund ordersRefund : ordersRefunds) {
            Orders orders = ordersManagerService.getById(ordersRefund.getId());
            ordersManagerService.requestRefundOrder(ordersRefund.getId(), ordersRefund.getRealPayAmount(), orders.getTradingOrderNo());
        }
    }
}
